﻿using System;
using System.Linq;
using System.Linq.Expressions;
using SBACN.WebSite.Code;
using SBACN.WebSite.Common;
using SBACN.WebSite.Models;
using System.Collections.Generic;

namespace SBACN.WebSite.Admin.MemberService.Education
{
	public partial class ExamSubjectList : AdminBasePage
	{
		/// <summary>
		/// 系统字典类型
		/// </summary>
		public string SystemType
		{
			get
			{
				return this.SystemCode;
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if(!Page.IsPostBack)
			{
				Search_List();
			}
		}

		private void Search_List()
		{
			Expression<Func<TB_Examination, bool>> fun = (p => true);
			Expression<Func<TB_Examination, DateTime>> order = (p => p.Deadline);
			int records = 0;
			this.ExamList.DataSource = DAL.DALHelper.Instance.GetList<TB_Examination, DateTime>(fun, order, false, this.Pager1.PageSize, Pager1.CurrentPageIndex, out records);
			this.ExamList.DataBind();
			this.Pager1.RecordCount = records;
			this.Pager1.InitControl();
		}

		public void BindSelectedPageIndexChanged(int pageIndex, int nextPage)
		{
			Pager1.CurrentPageIndex = nextPage;
			Search_List();
		}

		#region UploadScoreFile
		protected void ScoreUpLoadSubbtn_Click(object sender, EventArgs e)
		{
			int ExamID = Convert.ToInt32(this.HidSubjectID.Value);
			string extension = GetFileExt(this.FileUploadScore.FileName);
			if (this.FileUploadScore.FileBytes.Length == 0 || this.FileUploadScore.FileBytes.Length > (MaxUploadSize * 1024 * 1024))
			{
				ClientScript.RegisterClientScriptBlock(this.GetType(),"AlertMsg","<script type='text/javascript'>alert('上传的文件大小不符合系统设置,请重新上传！');</script>");
				return;
			}
			else if ((",xlsx,xls,").ToLower().IndexOf(("," + extension + ",").ToLower()) < 1)
			{
				ClientScript.RegisterClientScriptBlock(this.GetType(),"AlertMsg","<script type='text/javascript'>alert('上传的文件格式不正确,请重新上传！');</script>");
				return;
			}
			else
			{
				#region UpLoadFile
				string Url = BasePage.UploadFile(this.SystemType, this.FileUploadScore.FileName, this.FileUploadScore.FileBytes);
				TB_UploadInfo upload = DAL.DALHelper.Instance.Create<TB_UploadInfo>();
				upload.CreateBy = AdminInfo.UserName;
				upload.CreateDate = DateTime.Now;
				upload.FilePath = Url;
				upload.FileType = BasePage.GetFileExt(this.FileUploadScore.FileName);
				upload.Name = "考试成绩上传";
				upload.PrimaryID = ExamID;
				upload.Type = this.SystemType;
				DAL.DALHelper.Instance.Add<TB_UploadInfo>(upload);
				DAL.DALHelper.Instance.SaveChanges();
				#endregion

				#region WriteScour
				int ExamID_N = 0;
				string ExamName = string.Empty;
				if (int.TryParse(this.HidSubjectID.Value, out ExamID_N))
				{
					var resultExam = DAL.DALHelper.Instance.GetObject<TB_Examination>("ID", ExamID_N);
					if (resultExam != null)
					{
						ExamName = resultExam.Subject;
					}
				}

				string sheel = "Sheet1";
				var DI = ExcelAccess.GetExcelRows(Server.MapPath(Url), sheel);
				if (DI.Tables[0].Columns.Count >= 5 && DI.Tables[0].Columns.Contains("科目") && DI.Tables[0].Columns.Contains("身份证号码") && DI.Tables[0].Columns.Contains("业务成绩") && DI.Tables[0].Columns.Contains("政策成绩") && DI.Tables[0].Columns.Contains("一般成绩") && DI.Tables[0].Columns.Contains("姓名"))
				{
					if (DI.Tables[0].Rows.Count <= 0) {
						ClientScript.RegisterClientScriptBlock(this.GetType(), "AlertMsg", "<script type='text/javascript'>alert('文件中没有数据，请确认后重新上传！');</script>");
						return;
					}

					if (string.IsNullOrWhiteSpace(ExamName) || DI.Tables[0].Rows[0]["科目"] == null || DI.Tables[0].Rows[0]["科目"].ToString() != ExamName)
					{
						ClientScript.RegisterClientScriptBlock(this.GetType(),"AlertMsg","<script type='text/javascript'>alert('文件中的考试科目与目标考试科目不匹配，请确认后重新上传！');</script>");
						return;
					}
					else
					{
						bool allDataIsRight = true;
						var list = new List<TB_Score>();
						var userlist = DAL.DALHelper.Instance.GetList<TB_Score>(p => p.ExamID == ExamID_N);
						string msg = string.Empty;
						for (int i = 0; i < DI.Tables[0].Rows.Count; i++)
						{
							var personscore = userlist.Where(p => p.IDCardNO == DI.Tables[0].Rows[i]["身份证号码"].ToString() && p.Name == DI.Tables[0].Rows[i]["姓名"].ToString()).FirstOrDefault();
							if (personscore != null)
							{
								personscore.Score = DI.Tables[0].Rows[i]["一般成绩"] == null ? "" : DI.Tables[0].Rows[i]["一般成绩"].ToString();
								personscore.ScoreProfession = DI.Tables[0].Rows[i]["业务成绩"] == null ? "" : DI.Tables[0].Rows[i]["业务成绩"].ToString();
								personscore.ScorePolicy = DI.Tables[0].Rows[i]["政策成绩"] == null ? "" : DI.Tables[0].Rows[i]["政策成绩"].ToString();
								list.Add(personscore);
							}
							else
							{
								msg += "姓名:" + DI.Tables[0].Rows[i]["姓名"].ToString() + ",身份证号:" + DI.Tables[0].Rows[i]["身份证号码"].ToString() + "\\r\\n";
								allDataIsRight = false;
							}
						}

						if(!string.IsNullOrWhiteSpace(msg))
						{
							ClientScript.RegisterClientScriptBlock(this.GetType(),"AlertMsg","<script type='text/javascript'>alert(\"上传的文件内容不正确:\\r\\n" + msg + "有误,请重新上传！\");</script>");
							return;
						}
						else if (allDataIsRight && list.Count > 0)
						{
							foreach (var user in list)
							{
								DAL.DALHelper.Instance.Update(user);
							}
							DAL.DALHelper.Instance.SaveChanges();
							ClientScript.RegisterClientScriptBlock(this.GetType(), "AlertMsg", "<script type='text/javascript'>alert('成绩上传成功！');</script>");
							return;
						}
					}
				}
				else
				{
					ClientScript.RegisterClientScriptBlock(this.GetType(),"AlertMsg","<script type='text/javascript'>alert('上传的文件内容格式不正确，请重新上传！');</script>");
					return;
				}
				#endregion
			}
			Search_List();
		}
		#endregion

		protected void btn_Delete_Click(object sender, EventArgs e)
		{
			int ID = Convert.ToInt32(this.hid_ID.Value);

			var resultExam = DAL.DALHelper.Instance.GetObject<TB_Examination>("ID", ID);
			if (resultExam.Status == 1)
			{
				resultExam.Status = 0;

			}
			else
			{
				resultExam.Status = 1;
			}
			DAL.DALHelper.Instance.Update<TB_Examination>(resultExam);
			DAL.DALHelper.Instance.SaveChanges();
			Response.Redirect(Request.Url.ToString());
		}

		protected void btn_NewsRefresh_Click(object sender, EventArgs e)
		{
			Search_List();
		}
	}
}